/**
 * 
 */
package com.vit.mep.manager;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.crypto.CryptoException;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.w3c.dom.Document;

import com.vit.mep.HttpPost;
import com.vit.mep.MepException;
import com.vit.mep.model.BankResponse;
import com.vit.mep.model.MepUser;
import com.vit.mep.model.TransactionData;

/**
 * @author crodriguez
 * 
 */
public class TransactionManager {

	public BankResponse authTransaction(MepUser mepUser, TransactionData tdata)
			throws IOException, MepException, CryptoException {

		// URLEncodedPostData _postData = new URLEncodedPostData("",false);

		String resultXml = "";
		ManagerUtils utils = new ManagerUtils();

		// tdata.setMonto(utils.convertToHex(utils.encrypt(
		// tdata.getMonto().getBytes()).getBytes()));
		// tdata.setExpDate(utils.convertToHex(utils.encrypt(tdata.getExpDate().getBytes()).getBytes()));
		tdata.setCardNumber(utils.convertToHex(utils.encrypt(
				tdata.getCardNumber().getBytes()).getBytes()));
		tdata.setCvv(utils.convertToHex(utils
				.encrypt(tdata.getCvv().getBytes()).getBytes()));
		
		//validaciones temporales para test
		

		/*
		 * String postUrl = "?user=" + mepUser.getUsername() //no va +
		 * "&password=" + mepUser.getPassword() //no va + "&dui=" +
		 * tdata.getDui() + "&email=" + tdata.getEmail() + "&monto="+
		 * tdata.getMonto() + "&expdate="+ tdata.getExpDate() //encriptar +
		 * "&cardnumber="+ tdata.getCardNumber() //encriptar + "&cvv="+
		 * tdata.getCvv()//encriptar + "&format=xml";
		 */

		String val = saveCreditCardWs(tdata.getEmail(), tdata.getDui(),
				tdata.getMonto(), "1", "1", "venta de articulo electronico",
				tdata.getCardNumber(), tdata.getCvv(), tdata.getExpDate());

		//Dialog.alert("menesaje fue: " + val);

		// HttpPost _httpPost=new HttpPost(ManagerConstants._AUTH_SERVICE +
		// postUrl , _postData,"POST");
		// resultXml=_httpPost.executeMethodPOST_INPUT_DELETE();
		BankResponse br;
		try {
			br = parseResult(resultXml);
		} catch (Exception e) {
			MepException me = new MepException();
			me.setAditionalMessage("Error en respuesta de transaccion:"
					+ e.getMessage());
			throw me;
		} finally {
			// _httpPost.closeConnection();
		}
		return br;
	}

	private BankResponse parseResult(String xml) throws Exception {
		BankResponse br = new BankResponse();

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
		Document doc = db.parse(bis);
		doc.normalize();

		ManagerUtils mu = new ManagerUtils();
		String value = mu.getUniqueNodeValue("id", doc);
		br.setId(value);
		value = mu.getUniqueNodeValue("auth", doc);
		br.setAuth(value);
		value = mu.getUniqueNodeValue("ref", doc);
		br.setRef(value);
		value = mu.getUniqueNodeValue("comercio", doc);
		br.setComercio(value);
		value = mu.getUniqueNodeValue("rescode", doc);
		br.setResultCode(value);
		value = mu.getUniqueNodeValue("resMsg", doc);
		br.setResultMsg(value);
		value = mu.getUniqueNodeValue("other", doc);
		br.setOtherMsg(value);
		return br;
	}

	public String saveCreditCardWs(String email, String dui, String cantidad,
			String idcomercio, String idUsuario, String tipoTrans,
			String creditCard, String cvv, String strFecha) {

		try {

			String nameSpace = "http://webServices";
			String methodName = "createCreditCardTrans";
			String soapAction = nameSpace + "/" + methodName;

			String URL = "http://localhost:8080/MepWs/services/MepWs;deviceside=true";

			SoapObject soapObj = new SoapObject(nameSpace, methodName);
			soapObj.addProperty("email", email);
			soapObj.addProperty("dui", dui);
			soapObj.addProperty("cantidad", cantidad);
			soapObj.addProperty("idcomercio", idcomercio);
			soapObj.addProperty("idUsuario", idUsuario);
			soapObj.addProperty("tipoTrans", tipoTrans);
			soapObj.addProperty("creditCard", creditCard);
			soapObj.addProperty("cvv", cvv);
			soapObj.addProperty("strFecha", strFecha);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
			envelope.bodyOut = soapObj;
			envelope.dotNet = false;

			HttpTransport httpTrans = new HttpTransport(URL);

			httpTrans.debug = true;

			String result = null;
			
			try {

				httpTrans.call(soapAction, envelope);

				result = envelope.getResponse().toString();
				return result.toString();

			} catch (org.xmlpull.v1.XmlPullParserException ex2) {

				return ex2.toString();
			}

		} catch (Exception ex) {

			return ex.toString();

		}

	}

	protected String createXML(MepUser user) {
		ManagerUtils mu = new ManagerUtils();
		String xml = "";
		String usr = mu.inXmlTag("usuario", user.getUsername());
		String pass = mu.inXmlTag("password",mu.generateEncrypted(user.getPassword()));
		xml += "<mep>";
		xml += usr + pass;
		xml += "</mep>";
		return xml;
	}

	public String MD5(String data) {
		// TODO: encriptar
		// ManagerUtils mu = new ManagerUtils();
		return "";
	}

}// class